package ar.com.age.distribuidora.presentacion.controller;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import ar.com.age.distribuidora.dominio.Cliente;
import ar.com.age.distribuidora.presentacion.util.ServiceLocator;

@ManagedBean
@ViewScoped
public class ReporteBean {
	
	private List<Cliente> clientes = null;
	public List<Cliente> getClientes() {
		return  clientes =  ServiceLocator.getClienteService().buscarTodos();
	}

	public void setClientes(List<Cliente> clientes) {
		this.clientes = clientes;
	}
	
	public void exportarPDF() throws JRException, IOException{
		Map<String, Object> parametros = new HashMap<String, Object>();
		parametros.put("txtUsuario", "Gustavo");

		File jasper= new File(FacesContext.getCurrentInstance().getExternalContext().getRealPath("/jasper/reporteColorido.jasper"));
		JasperPrint jasperPrint= JasperFillManager.fillReport(jasper.getPath(), parametros,new JRBeanCollectionDataSource(getClientes()));
	
		HttpServletResponse response= (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
		response.addHeader("Content-disposition","attachment; filename=jsfReporte.pdf");
		ServletOutputStream stream= response.getOutputStream();
		
		JasperExportManager.exportReportToPdfStream(jasperPrint, stream);
		stream.flush();
		stream.close();
		
		FacesContext.getCurrentInstance().responseComplete();
	}
}
